/* ************************************************************************
> File Name:     8.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年04月30日 星期六 11时24分06秒
> Description:   
 ************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>

int main(void)
{
    FILE *f1 = fopen("test.txt", "a+");

    if (!f1){
        perror("open file test.txt");
        exit(1);
    }

    char s[30];
    int i = -1;
    int size;

    while (1){
        time_t t = time(NULL);
        time_t *pt = &t;
        struct tm *ptt;
        ptt = localtime(pt);

        //fflush(f1); //可以不同因为fgets是先去缓冲区取，写不写回文件无所谓
        rewind(f1);
        if (fgets(s, 30, f1) == NULL){
            i = 0;
        }
        else{
            if (i == 0){
                fseek(f1, -22, SEEK_END);
            }
            else{
                fseek(f1, -21, SEEK_END);
                char c;
                while ((c = fgetc(f1)) != '\n'){
                    fseek(f1, -2, SEEK_CUR); //注意每次读取完之后位置会发生变化
                }
            }

            fscanf(f1, "%d", &i);
        }

        fseek(f1, 0, SEEK_END);
        sprintf(s, "%d %d-%.2d-%.2d %.2d:%.2d:%.2d\n", i + 1 ,\
                1900 + ptt->tm_year, 1 + ptt->tm_mon, ptt->tm_mday, ptt->tm_hour, ptt->tm_min, ptt->tm_sec);
        if (fputs(s, f1) == EOF){
            perror("write file test.txt");
        }
        
        sleep(1);
    }

    fclose(f1);
    
    return 0;
}
